import { cache } from "@/utility/Cache";
import { Result } from "@/utility/Tool";
import getConfig from "./config";

function http(method:Method,path:string):MethodDecorator{
	return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor): void => {
	    descriptor.value = <T>(data: any): Promise<Result<T>> => {
	        return request({
				path,
				method,
				params:data
			})
	    }
	}
}
function uniRequest<T>(options: UniNamespace.RequestOptions) :Promise<Result<T>>{
	return new Promise<Result<T>>((resolve,_)=>{
		uni.request({
			...options,
			success: (res) => {
				const response = res.data as Result<T>
				resolve(response)
			},
			fail: (error) => {
				resolve(new Result<T>(-1,error.errMsg))
			}
		})
	})
}
type Method = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
async function request<T>(data: {
  path: string;
  method: Method;
  params?: any;
  header?: any;
}): Promise<Result<T>> {
	let config = getConfig()
	let url = config.baseURL + data.path
	// #ifdef H5
	url = "/" + config.environment + data.path
	// #endif

	let token = await cache.stringValue("token")
	let baseHeader = {
		"x-flag":"android",
		"platform-flag":"mall",
		"version":config.version,
		"Authorization" : token ?? ""
	}
	Object.assign(baseHeader,data.header)
	return uniRequest<T>({
		url:url,
		method:data.method,
		data:data.params,
		header:baseHeader,
	})
}



export const GET = (path: string): MethodDecorator => {
    return http("GET",path)
}
export const POST = (path: string): MethodDecorator => {
    return http("POST",path)
}


